#include "devlist_model.h"
#include "devlist_data.h"
#include <QMimeData>
#include <QDataStream>

DevlistModel::DevlistModel(const QStringList& headers, QObject *parent)
: TreeModel(headers, parent)
{
}

//void DevlistFilterModel::SetSearchText(const QString& text)
//{
//    mStrSearch = text;
//    invalidateFilter();
//}
	
//bool DevlistFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
//{
//    QModelIndex source_index = sourceModel()->index(source_row, 0, source_parent);
//    bool filter = source_index.data(Qt::ToolTipRole).toString().contains(mStrSearch, Qt::CaseInsensitive);
//    if (filter)
//    {
//        return true;
//    }
//    else
//    {
//        for (int i = 0; i < sourceModel()->rowCount(source_index); i++)
//        {
//            if (filterAcceptsRow(i, source_index))
//            {
//                return true;
//            }
//        }
//    }

//    return false;
//}


Qt::ItemFlags DevlistModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())  return Qt::NoItemFlags;

    Qt::ItemFlags flags = QAbstractItemModel::flags(index);
    TreeItem* item =  index.data(Qt::UserRole).value<TreeItem*>();
    if (item && item->DataType() == TREE_DATA_TYPE_DEVICE)
    {
       flags |= Qt::ItemIsDragEnabled;
    }
    return flags;
}
QStringList DevlistModel::mimeTypes() const
{
    QStringList types;
    types << "application/dev.list";//此处只支持纯文本类
    return types;
}
QMimeData *DevlistModel::mimeData(const QModelIndexList &indexes) const
{
    //QMimeData* mimeData = QAbstractItemModel::mimeData(indexes);
    //在进行拖放操作之前，需要将数据放入到一个QMimeData类型的对象中
    QMimeData *mime_data = new QMimeData();
    QByteArray encoded_data;
    QDataStream stream(&encoded_data, QIODevice::WriteOnly);
    foreach(const QModelIndex &index, indexes)
    {
        if(index.isValid())
        {
            TreeItem *item = itemFromIndex(index);
            stream << (qint64)item;
            break;
        }
    }
    //将数据放入QMimeData中
    mime_data->setData("application/dev.list", encoded_data);
    return mime_data;

}
Qt::DropActions DevlistModel::supportedDragActions() const
{
    return Qt::CopyAction | Qt::MoveAction;//复制和移动
}
//bool DevlistModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
//{
//}
//bool DevlistModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
//{
////如果放入的动作是Qt::IgnoreAction，那么返回true
//if(action == Qt::IgnoreAction){
//    return true;
//}
////如果数据的格式不是指定的格式，返回false
//if(!data->hasFormat("application/dev.list")){
//    return false;
//}
////将数据从QMimeData中读出来，然后插入到模型中
//QByteArray encoded_data = data->data("application/vnd.text.list");
//QDataStream stream(&encoded_data, QIODevice::ReadOnly);
//qint64 p;
//stream >> p;
//TreeItem *item = (TreeItem*)p;
//}
